<template>
  <div
    class="widget-view widget_tabs"
    :class="{
      active: selectWidget.key == element.key,
    }"
    @click.stop="handleSelectWidget"
  >
    <el-tabs
      v-model="active"
      :type="element.options.type"
      :key="element.key"
      :tab-position="element.options.tabPosition"
    >
      <el-tab-pane
        v-for="(tab, tabIndex) in element.tabs"
        class="el_tab_pane"
        :key="`${element.key}_${tabIndex}`"
        :label="tab.label"
        :name="tab.name"
      >
        <draggable
          :list="element.tabs[tabIndex].list"
          :no-transition-on-drag="true"
          v-bind="{
            group: 'widgets',
            ghostClass: 'ghost',
            animation: 200,
            handle: '.drag-widget',
          }"
          @end.stop="handleMoveEnd"
          @add.stop="handleWidgetTabAdd($event, element, tabIndex)"
        >
          <transition-group name="fade" tag="div" class="widget-tab-list">
            <template v-for="(el, i) in tab.list">
              <template v-if="el.type === 'flexContainer'">
                <widget-form-flex-container
                  v-if="el && el.key"
                  :key="el.key"
                  :element="el"
                  :select.sync="selectWidget"
                  :index="i"
                  :data="tab"
                />
              </template>
              <template v-else-if="el.type === 'group'">
                <widget-form-group
                  v-if="el && el.key"
                  :key="el.key"
                  :element="el"
                  :select.sync="selectWidget"
                  :index="i"
                  :data="tab"
                  :remote="remote"
                />
              </template>
              <template v-else>
                <widget-form-item
                  :key="el.key"
                  v-if="el.key"
                  :element="el"
                  :select.sync="selectWidget"
                  :index="i"
                  :data="tab"
                />
              </template>
            </template>
          </transition-group>
        </draggable>
      </el-tab-pane>
    </el-tabs>
    <div
      class="widget-view-action widget-tabs-action"
      v-if="selectWidget.key == element.key"
    >
      <i class="iconfont icon-trash" @click.stop="handleWidgetDelete(index)" />
    </div>

    <div
      class="widget-view-drag widget-tabs-drag"
      v-if="selectWidget.key == element.key"
    >
      <i class="iconfont icon-drag drag-widget" />
    </div>
  </div>
</template>

<script>
import Draggable from 'vuedraggable'
import WidgetFormItem from './WidgetFormItem'
import WidgetFormFlexContainer from './WidgetFormFlexContainer.vue'

import {
  basicComponents,
  layoutComponents,
  advanceComponents,
} from '../configs/componentsConfig.js'
import WidgetFormGroup from './WidgetFormGroup.vue'
export default {
  components: {
    Draggable,
    WidgetFormItem,
    WidgetFormFlexContainer,
    WidgetFormGroup,
  },
  props: {
    element: {
      type: Object,
    },
    select: {
      type: Object,
    },
    index: {
      type: Number,
    },
    data: {
      type: Object,
    },
    remote: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      basicComponents,
      layoutComponents,
      advanceComponents,
      selectWidget: this.select,
      active: null,
    }
  },
  created() {},
  mounted() {
    this.active = this.element.tabs[0].name
    this.$nextTick(() => {
      this.selectWidget = this.element
    })
  },
  methods: {
    handleWidgetTabAdd($event, tabs, tabIndex) {
      const newIndex = $event.newIndex
      const oldIndex = $event.oldIndex
      const item = $event.item
      const key =
        Date.parse(new Date()) + '_' + Math.ceil(Math.random() * 99999)

      let tmp = {
        ...tabs.tabs[tabIndex].list[newIndex],
        options: {
          ...tabs.tabs[tabIndex].list[newIndex].options,
          remoteFunc: 'func_' + key,
        },
        key,
        // 绑定键值
        model: tabs.tabs[tabIndex].list[newIndex].type + '_' + key,
        rules: [],
      }

      if (
        tabs.tabs[tabIndex].list[newIndex].type === 'radio' ||
        tabs.tabs[tabIndex].list[newIndex].type === 'checkbox' ||
        tabs.tabs[tabIndex].list[newIndex].type === 'select' ||
        tabs.tabs[tabIndex].list[newIndex].type === 'refusecode'
      ) {
        tmp = {
          ...tmp,
          options: {
            ...tabs.tabs[tabIndex].list[newIndex].options,
            options: tabs.tabs[tabIndex].list[newIndex].options.options.map(
              (item) => ({
                ...item,
              })
            ),
          },
        }
      }

      if (
        tabs.tabs[tabIndex].list[newIndex].type === 'grid' ||
        tabs.tabs[tabIndex].list[newIndex].type === 'flexContainer'
      ) {
        const columns = tabs.tabs[tabIndex].list[newIndex].columns || []
        tmp = {
          ...tmp,
          columns: columns.map((item) => ({
            ...item,
          })),
        }
      }

      if (tabs.tabs[tabIndex].list[newIndex].type === 'form') {
        // 通过模板添加内容
        const preWidgets = JSON.parse(
          JSON.stringify(tabs.tabs[tabIndex].list.slice(0, newIndex))
        )
        const sufWidgets = JSON.parse(
          JSON.stringify(tabs.tabs[tabIndex].list.slice(newIndex + 1))
        )
        tmp.form.list.forEach((formItem) => {
          const widget = this.generateWidget(formItem)
          preWidgets.push(widget)
        })
        this.$set(tabs.tabs[tabIndex], 'list', [...preWidgets, ...sufWidgets])
      } else {
        this.$set(tabs.tabs[tabIndex].list, newIndex, tmp)
      }

      this.selectWidget = tabs.tabs[tabIndex].list[newIndex]
    },
    handleWidgetDelete(index) {
      if (this.data.list.length - 1 === index) {
        if (index === 0) {
          this.selectWidget = {}
        } else {
          this.selectWidget = this.data.list[index - 1]
        }
      } else {
        this.selectWidget = this.data.list[index + 1]
      }

      this.$nextTick(() => {
        this.data.list.splice(index, 1)
      })
    },
    handleMoveEnd() {},
    generateWidget(widget) {
      let tmp = JSON.parse(JSON.stringify(widget))
      const key =
        Date.parse(new Date()) + '_' + Math.ceil(Math.random() * 99999)
      tmp = {
        ...tmp,
        key,
        model: `${tmp.type}_${key}`,
      }
      if (widget.type === 'tabs') {
        const tabs = tmp.tabs.map((item) => {
          const list = item.list.map((subItem) => {
            return this.generateWidget(subItem)
          })
          return {
            ...item,
            list,
          }
        })
        tmp.tabs = tabs
      } else if (widget.type === 'grid' || widget.type === 'flexContainer') {
        const columns = tmp.columns.map((item) => {
          const list = item.list.map((subItem) => {
            return this.generateWidget(subItem)
          })
          return {
            ...item,
            list,
          }
        })
        tmp.columns = columns
      }
      // const noModelLabels = ['blank', 'grid', 'tabs', 'flexContainer']
      return tmp
    },
    handleSelectWidget() {
      this.selectWidget = this.element
    },
    checkMove(evt) {
      console.log('check move =================')
      console.log(evt)
      console.log('=================')
      return true
    },
  },
  watch: {
    select(val) {
      this.selectWidget = val
    },
    selectWidget: {
      handler(val) {
        this.$emit('update:select', val)
      },
      deep: true,
    },
    'element.tabs': {
      handler(val) {
        if (!val.find((item) => item.name === this.active)) {
          this.active = val[0].name
        }
      },
      deep: true,
    },
  },
}
</script>

<style lang="scss" scoped>
.widget_tabs {
  padding: 20px 0;
  &.active {
    outline-color: #e6a23c !important;
    border-color: #e6a23c !important;
  }
  .widget-view-drag,
  .widget-view-action {
    background: #e6a23c !important;
  }
  .el_tab_pane {
    padding: 0 10px;
  }
  .widget-tab-list {
    min-height: 60px;
    background: none;
    border: 1px solid #ccc;
  }
}
</style>
